<template>
  <!-- 音频上传 -->
  <el-dialog
    title="音频上传"
    class="dialogInsertImage"
    :visible.sync="audioDialog"
    :append-to-body="true"
    :before-close="handleClose"
  >
    <el-upload
      class="avatar-uploader"
      :action="
        '  https://pc.mabababiancheng.com/community/article/article/uploadImage?token=' +
        Utoken
      "
      :limit="1"
      drag
      :data="audioType"
      :show-file-list="true"
      :multiple="true"
      :before-upload="beforeAvatarUpload"
      :on-success="(res) => onUploadAudio(res)"
    >
      <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
    </el-upload>
  </el-dialog>
</template>

<script>
export default {
  name: "froala-insertAudio",
  props: ["audioDialog", "Utoken"],
  data() {
    return {
      audioType: {
        type: 8,
      },
      fileName: "",
      playTime: 0,
    };
  },
  methods: {
    handleClose() {
      this.$emit("closeDialog");
    },

    onUploadAudio(res) {
      var html = `<audio controls src="${res.link}" class="fr-draggable" data-fileName="${this.fileName}" data-playTime="${this.playTime}"></audio>`;
      this.$emit("insertImage", html);
      this.$emit("closeDialog");
    },

    beforeAvatarUpload(file) {
      const isImg = file.type === "audio/mpeg" || file.type === "audio/mp3";
      this.fileName = file.name;
      if (!isImg) {
        this.$message.error("请上传音频!");
      }
      let url = URL.createObjectURL(file);
      let audioElement = new Audio(url);
      audioElement.addEventListener("loadedmetadata", (_event) => {
        let playTime = audioElement.duration;
        this.playTime = playTime;
      });
      return isImg;
    },
  },
};
</script>

<style lang="scss" scoped>
.dialogInsertImage ::v-deep .el-upload-dragger {
  width: auto;
  height: auto;
}
.el-upload-list__item-actions {
  &.isLoading {
    opacity: 1;
    span {
      display: inline-block;
    }
  }
}
::v-deep .el-upload-dragger .el-upload__text {
  height: 200px;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 200px;
}
</style>
